<template>
  <el-form ref="formData" :model="formData" :rules="rules" label-width="80px">
    <el-form-item
      label="所属学科"
      prop="subjectID"
      :hidden="this.query.subjectID"
    >
      <el-select v-model="formData.subjectID" placeholder="请选择">
        <el-option
          v-for="item in Subject"
          :key="item.label"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="目录名称" prop="directoryName">
      <el-input
        v-model="formData.directoryName"
        placeholder="请输入目录名称"
      />
    </el-form-item>
    <el-button @click="Cancel">取 消</el-button>
    <el-button type="primary" @click="confirm">确定</el-button>
  </el-form>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/directorys.js'
import { simple } from '@/api/hmmm/subjects'
export default {
  name: 'DirectorysAdd',
  props: {
    id: {
      type: Number,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    query: {
      type: Object
    }
  },
  data() {
    return {
      Subject: [], // 所属学科列表
      formData: {
        subjectID: Number(this.query.subjectID) ? Number(this.query.subjectID) : '',
        directoryName: ''
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 调用获取学科简单列表的方法
    this.simpleSub()
    this.detail()
  },
  methods: {
    // 确认按钮
    confirm() {
      this.$refs.formData.validate(async(valid) => {
        if (!valid) return

        this.isEdit ? this.update() : this.addSubject()
        this.$emit('addSub')
      })
    },

    // 编辑完成
    async update() {
      const res = await update(this.formData)
      // console.log(res)
      if (res.status === 200) {
        this.$message.success('编辑目录成功')
      }
    },

    // 编辑数据回显
    async detail() {
      if (this.isEdit) {
        const res = await detail({ id: this.id })
        // console.log(res)
        this.formData = res.data
      }
    },

    // 获取学科简单列表
    async simpleSub() {
      // 调用所属学科的 API
      const res = await simple()
      // 渲染数据
      this.Subject = res.data
    },

    // 添加学科
    async addSubject() {
      if (!this.isEdit) {
        // 调用新增目录的 API
        const res = await add(this.formData)

        // console.log(res)
        if (res.status === 200) {
          // 添加成功，给用户进行提示
          this.$message.success('新增目录成功')
        }
      }
    },

    // 取消弹框
    Cancel() {
      // 传值父组件
      this.$emit('clone')
    }
  }
}
</script>

<style scoped >
button.el-button.el-button--default.el-button--medium {
  margin-left: 188px;
}
span.el-input__suffix {
  margin-right: 8px;
}
.el-select.el-select--medium {
  width: 100%;
}
</style>
